package com.un.ebs.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.un.ebs.core.UserContext;
import com.un.ebs.core.util.SecurityUtils;
import com.un.ebs.core.util.StringUtils;
import com.un.ebs.core.util.WebResult;
import com.un.ebs.core.util.WebUtils;
import com.un.ebs.sys.domain.DictionaryKey;
import com.un.ebs.sys.domain.DictionaryValueExt;
import com.un.ebs.sys.dto.*;
import com.un.ebs.sys.mapper.DictionaryKeyMapper;
import com.un.ebs.sys.service.DictionaryAreaService;
import com.un.ebs.sys.service.DictionaryKeyService;
import com.un.ebs.sys.service.DictionaryValueService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author liubo
 * @since 2019-09-25
 */
@RestController
@RequestMapping("/dictionary")
@Api(value = "sys-dictionary", description = "字典")
public class DictionaryController {

    @Autowired
    private DictionaryKeyService dictionaryKeyService;

    @Autowired
    private DictionaryValueService dictionaryValueService;

    @Autowired
    private DictionaryAreaService dictionaryAreaService;

    @Autowired
    private DictionaryKeyMapper dictionaryKeyMapper;


    @GetMapping("/area")
    @ApiOperation(value = "查询地区代码", notes = "如果")
    public WebResult listArea(@RequestParam(value = "parentId", required = false) Integer parentId) {
        return WebUtils.success(dictionaryAreaService.query(parentId));
    }

    @PostMapping("addKey")
    @ApiOperation(value = "addKey", notes = "添加")
    public WebResult saveKey(@RequestBody @Valid DictionaryKeyAddDto req) {
        dictionaryKeyService.add(req);
        return WebUtils.success();
    }

    @PostMapping("addValue")
    @ApiOperation(value = "addValue", notes = "添加")
    public WebResult saveValue(@RequestBody @Valid DictionaryValueAddDto req) {
        dictionaryValueService.add(req);
        return WebUtils.success();
    }

    @PostMapping("updateKey")
    @ApiOperation(value = "updateKey", notes = "修改")
    public WebResult updateKey(@RequestBody @Valid DictionaryKeyUpdateDto req) {
        if (StringUtils.isNullOrEmpty(req.getId())) {
            dictionaryKeyService.add(req);
        } else {
            dictionaryKeyService.update(req);
        }
        return WebUtils.success();
    }

    @PostMapping("updateValue")
    @ApiOperation(value = "updateValue", notes = "修改")
    public WebResult updateValue(@RequestBody @Valid DictionaryValueUpdateDto req) {
        dictionaryValueService.update(req);
        return WebUtils.success();
    }

    @PostMapping("deleteValue/{id}")
    @ApiOperation(value = "deleteValue", notes = "根据主键删除单个 DictionaryValue")
    public WebResult deleteValue(@PathVariable("id") String id) {
        dictionaryValueService.delete(id);
        return WebUtils.success();
    }

    @PostMapping("deleteKey/{id}")
    @ApiOperation(value = "deleteKey", notes = "根据主键删除单个 DictionaryKey")
    public WebResult deleteKey(@PathVariable("id") String id) {
        dictionaryKeyService.delete(id);
        return WebUtils.success();
    }

    @PostMapping("changeNode")
    @ApiOperation(value = "changeNode", notes = "批量修改节点中的父级对象和排序")
    public WebResult changeNode(@RequestBody List<ObjectParentAndIndexChangeDto> nodes) {
        dictionaryValueService.changeNode(nodes);
        return WebUtils.success();
    }

    @GetMapping("listKey")
    @ApiOperation(value = "listKey", notes = "查询当前应用下所有的Key")
    public WebResult listAll() {
        UserContext userContext = SecurityUtils.getUserContent();
        LambdaQueryWrapper<DictionaryKey> lq = Wrappers.lambdaQuery();
        lq.eq(DictionaryKey::getAppId, userContext.getAppId());
        return WebUtils.success(dictionaryKeyMapper.selectList(lq));
    }

    @GetMapping("listValueByKey/{key}")
    @ApiOperation(value = "listByKey", notes = "")
    public WebResult<List<DictionaryValueExt>> list(@PathVariable("key") String key) {
        return WebUtils.success(dictionaryValueService.queryValueByKey(key));
    }

    //    @Cacheable(value = "redisExpire1h",key = "'dict_key_'+#key")
    @GetMapping("listValueStruByKey/{key}")
    @ApiOperation(value = "listValueStruByKey", notes = "")
    public WebResult<List<DictionaryValueExt>> listValueStruByKey(@PathVariable("key") String key) {
        return WebUtils.success(getValueVo(dictionaryValueService.queryValueByKey(key)));
    }

    private List<DictionaryValueVo> getValueVo(List<DictionaryValueExt> list) {
        List<DictionaryValueVo> result = new ArrayList<>();
        List<DictionaryValueExt> rootList = list.stream().filter(s -> StringUtils.isNullOrEmpty(s.getParentId())).collect(Collectors.toList());
        for (DictionaryValueExt item : rootList) {
            DictionaryValueVo root = getValueVo(item);
            root.setChilds(getChildValueVo(list, item.getId()));
            result.add(root);

        }
        return result;
    }

    private List<DictionaryValueVo> getChildValueVo(List<DictionaryValueExt> list, String parentId) {
        if (StringUtils.isNullOrEmpty(parentId)) {
            return null;
        }
        List<DictionaryValueVo> result = new ArrayList<>();
        List<DictionaryValueExt> childs = list.stream().filter(s -> parentId.equals(s.getParentId())).collect(Collectors.toList());
        for (DictionaryValueExt item : childs) {
            DictionaryValueVo child = getValueVo(item);
            child.setChilds(getChildValueVo(list, item.getId()));
            result.add(child);
        }
        return result;
    }

    private DictionaryValueVo getValueVo(DictionaryValueExt obj) {
        DictionaryValueVo result = new DictionaryValueVo();
        BeanUtils.copyProperties(obj, result);
        return result;
    }

}